# 
# LTParser.rb
# 
# Created on Oct 21, 2007, 10:31:38 PM
# 
# To change this template, choose Tools | Templates
# and open the template in the editor.
 
require 'active_record'
require "fastercsv"

require File.join(File.dirname(__FILE__),'..','..','commonlib','book')
require File.join(File.dirname(__FILE__),'..','..','commonlib','author')
require File.join(File.dirname(__FILE__),'..','..','commonlib','tag')
require File.join(File.dirname(__FILE__),'..','..','commonlib','user')
require File.join(File.dirname(__FILE__),'..','..','commonlib','bookedition')
require File.join(File.dirname(__FILE__),'..','..','commonlib','bookreview')
require File.join(File.dirname(__FILE__),'..','..','commonlib','reading')
 
ActiveRecord::Base.logger = Logger.new(STDERR)
ActiveRecord::Base.colorize_logging = false

if ARGV.size == 2 or ARGV.size == 4 
  if ARGV[0] == '-db'
    db = ARGV[1]
  else if ARGV[0] == '-User'
      user = ARGV[1]
    end
  end
  if ARGV[2] == '-User'
    user = ARGV[3]
  else if ARGV[2] == '-db'
      db = ARGV[3]
    end
  end
end


ActiveRecord::Base.establish_connection(
  :adapter => "mysql",
  :host  => "localhost",
  :database => db
)

def parse_author_information (row)
  if row[2] != nil then
    rowAuthor = row[2].split(',')
    firstName = rowAuthor[1]
    lastName = rowAuthor[0]
    if firstName != nil then
      firstName = firstName.strip()
    end
    if lastName != nil then
      lastName = lastName.strip()
    end
  end
  author = Author.find_or_create_by_nameFirst_and_nameLast(firstName,lastName)
  return author
end

def parse_book_information(author, row)
  lTBookId = row[0]
  bookTitle = row[1]
  isbn = row[7]
  book = author.books.create(:LTWorkID => lTBookId, :title => bookTitle, :ISBN => isbn)
  return book
end

def parse_tag_information(book, userC, tagData)
  if tagData != nil then
    tagArray = tagData.split(',')
    for elt in tagArray
      tag = book.tags.find_or_create_by_tag(elt)
      tag.update_attributes(:user_id => userC.id)
    end
  end
  return tag
end

def create_user(usr)
  userC = User.find_or_create_by_loginID(usr)
  return userC
end

def create_edition_with_rating(book, userC, rating)
  edition = book.bookeditions.create(:rating => rating, :user_id => userC.id)
  return edition
end

def parse_review_information(edition, userC, review)
  if review != nil then
    edition.bookreviews.create(:review => review, :user_id => userC.id)
  end
end

FasterCSV.foreach("C:\\Documents\\LibraryDB\\LibraryThing_export_full.csv",
  :headers           => true,
  :header_converters => :symbol) do |row|
  userC = create_user(user)
  author = parse_author_information(row)
  book = parse_book_information(author, row)
  puts userC.id
  tag = parse_tag_information(book, userC, row[21])
  edition = create_edition_with_rating(book, userC, row[20])
  parse_review_information(edition, userC, row[22])
end   



